package com.haidechizi.i18n.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.google.common.base.Stopwatch;
import com.haidechizi.i18n.common.config.Configuration;
import com.haidechizi.i18n.common.constant.ParamConstant;
import com.haidechizi.i18n.common.execute.wapper.TranslateExecuteProxy;
import com.haidechizi.i18n.common.utils.GlobalUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 国际化dubbo filter，用于dubbo返回数据国际化
 */
@Slf4j
@Activate(group = Constants.PROVIDER)
public class I18nFilter implements Filter {

    private TranslateExecuteProxy translateExecuteProxy;

    private Configuration configuration;

    public TranslateExecuteProxy getTranslateExecuteProxy() {
        return translateExecuteProxy;
    }

    public void setTranslateExecuteProxy(TranslateExecuteProxy translateExecuteProxy) {
        this.translateExecuteProxy = translateExecuteProxy;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result rpcResult = invoker.invoke(invocation);
        try {
            // 通过隐式传参的方式解决部分服务不需要翻译的问题
            String translate = RpcContext.getContext().getAttachment(ParamConstant.TRANSLATE);
            if ("false".equals(translate)) {
                log.info("客户端跳过国际化翻译:,{},{}", translate, invocation.getMethodName());
                return rpcResult;
            }
            Stopwatch stopwatch = Stopwatch.createStarted();

            if (configuration.getDefaultLanguage().equals(GlobalUtils.getLanguage())) {
                log.error("language won't be translate! lang:{}", GlobalUtils.getLanguage());
                return rpcResult;
            }
            Object model = rpcResult.getValue();
            translateExecuteProxy.assembleI18nInfo(model);
            log.debug("国际化=====>：方法：{},具体耗时：{} ms", invocation.getMethodName(),
                    stopwatch.elapsed(TimeUnit.MILLISECONDS));

            return rpcResult;
        } catch (Throwable e) {
            log.error("I18nFilter error ", e);
            return rpcResult;
        }
    }
}
